package com.xsdlr.pipline;

import org.apache.http.client.fluent.Response;
import org.apache.http.impl.client.BasicResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import org.apache.http.client.fluent.Request;

import java.io.File;
import java.io.IOException;

/**
 * Created by xsdlr on 2017/3/21.
 */
@Component
public class ImageSavePipeline implements Pipeline {
    Logger logger = LoggerFactory.getLogger(ImageSavePipeline.class);

    private String basePath;

    public ImageSavePipeline() {
    }

    public ImageSavePipeline setBasePath(String basePath) {
        this.basePath = basePath;
        return this;
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        String id = resultItems.get("id");
        String name = resultItems.get("name");
        String imagePath = resultItems.get("img");
        logger.info("下载图片,id:{},学校:{},地址:{}", id, name, imagePath);
        try {
            String fileName = id == null ? name : id;
            File file = new File(basePath, fileName + ".jpg");
            Response response = Request.Get(imagePath).execute();
            response.saveContent(file);
        } catch (IOException e) {
            logger.error("下载图片失败", e);
        }
    }
}
